package com.ttg.common.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.concurrent.ThreadLocalRandom;

/**
 * Description：
 * Author: chenyou
 * Date: 2025/11/10 13:33
 * Company: ttg
 * Copyright: Copyright (c) 2025
 */
public class AmountGenerator {

    public static BigDecimal generateBigDecimal(BigDecimal min,
                                                         BigDecimal max,
                                                         int scale) {
        validateParameter(min.doubleValue(), max.doubleValue(), scale);

        BigDecimal range = max.subtract(min);

        double randomFactor = ThreadLocalRandom.current().nextDouble();
        BigDecimal randomAmount = min.add(range.multiply(BigDecimal.valueOf(randomFactor)))
                .setScale(scale, RoundingMode.HALF_UP);

        return randomAmount;
    }

    /**
     * 生成指定数量的随机金额（BigDecimal类型，推荐用于金融计算）
     */
    public static BigDecimal[] generateBigDecimalAmounts(int count,
                                                         BigDecimal min,
                                                         BigDecimal max,
                                                         int scale) {
        validateParameters(count, min.doubleValue(), max.doubleValue(), scale);

        BigDecimal[] amounts = new BigDecimal[count];
        BigDecimal range = max.subtract(min);

        for (int i = 0; i < count; i++) {
            double randomFactor = ThreadLocalRandom.current().nextDouble();
            BigDecimal randomAmount = min.add(range.multiply(BigDecimal.valueOf(randomFactor)))
                    .setScale(scale, RoundingMode.HALF_UP);
            amounts[i] = randomAmount;
        }

        return amounts;
    }

    private static void validateParameter( double min, double max, int decimalPlaces) {
        if (min > max || decimalPlaces < 0) {
            throw new IllegalArgumentException("参数不合法: min=" + min + ", max=" + max + ", decimalPlaces=" + decimalPlaces);
        }
    }

    private static void validateParameters(int count, double min, double max, int decimalPlaces) {
        if (count <= 0 || min > max || decimalPlaces < 0) {
            throw new IllegalArgumentException("参数不合法: count=" + count +
                    ", min=" + min + ", max=" + max + ", decimalPlaces=" + decimalPlaces);
        }
    }

}
